package com.leadcloud.nim.config.preference;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Build;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebView;

import com.alibaba.fastjson.JSONObject;
import com.leadcloud.nim.CommonCache;
import com.netease.nim.uikit.common.MyConst;
import com.netease.nim.uikit.common.util.log.LogUtil;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static org.json.Cookie.escape;

/**
 */
public class Preferences {
    private static final String KEY_USER_ACCOUNT = "account";
    private static final String KEY_USER_TOKEN = "token";
    private static final String KEY_USER_ID = "userId";
    private static final String KEY_ORG_ID = "orgId";
    private static final String KEY_USER_NAME = "userName";
    private static final String KEY_PWD = "password";
    private static final String KEY_REM_PWD = "remember_pwd";
    //"userId":406,"orgId":"10165"
    public static void saveUserAccount(String account) {
        saveString(KEY_USER_ACCOUNT, account);
    }

    public static String getUserAccount() {
        return getString(KEY_USER_ACCOUNT);
    }

    public static void saveUserToken(String token) {
        saveString(KEY_USER_TOKEN, token);
    }

    public static String getUserToken() {
        return getString(KEY_USER_TOKEN);
    }

    public static void saveUserId(String userId) {
        saveString(KEY_USER_ID, userId);
    }

    public static String getUserId() {
        return getString(KEY_USER_ID);
    }

    public static void saveOrgId(String orgId) {
        saveString(KEY_ORG_ID, orgId);
    }

    public static String getOrgId() {
        return getString(KEY_ORG_ID);
    }

    public static void saveString(String key, String value) {
        SharedPreferences.Editor editor = getSharedPreferences().edit();
        editor.putString(key, value);
        editor.commit();
    }

    private static void saveBoolean(String key, Boolean value) {
        SharedPreferences.Editor editor = getSharedPreferences().edit();
        editor.putBoolean(key, value);
        editor.apply();
    }

    public static String getString(String key) {
        return getSharedPreferences().getString(key, null);
    }
    private static Boolean getBoolean(String key) {
        return getSharedPreferences().getBoolean(key, false);
    }

    static SharedPreferences getSharedPreferences() {
        return CommonCache.getContext().getSharedPreferences("Demo", Context.MODE_PRIVATE);
    }

    public static void saveUserName(String userName) {
        saveString(KEY_USER_NAME, userName);
    }

    public static String getUserName() {
        return getString(KEY_USER_NAME);
    }

    public static void savePwd(String password) {
        saveString(KEY_PWD, password);
    }
    public static String getPwd() {
        return getString(KEY_PWD);
    }

    public static void saveRemenberPwd(boolean isSave) {
        saveBoolean(KEY_REM_PWD, isSave);
    }
    public static Boolean isRemenberPwd() {
        return getBoolean(KEY_REM_PWD);
    }

    public static List<String> getCookieList(){
        String loginInfo = Preferences.getString("loginInfo");
        ArrayList<String> result=new ArrayList<>();
        if(loginInfo!=null){
            JSONObject loginObj = JSONObject.parseObject(loginInfo);
            String acciId = loginObj.getString("acciId");
            String token = loginObj.getString("token");
            String userId = loginObj.getString("userId");
            String enterpriseId = loginObj.getString("orgId");
            String userName = getUserName();
            result.add(makeCookie("acciId",acciId));
            result.add(makeCookie("token",token));
            result.add(makeCookie("userId",userId));
            result.add(makeCookie("enterpriseId",enterpriseId));
            result.add(makeCookie("userName",userName));
        }

        return result;
    }

    private static String makeCookie(String name,String value){
        /*function setCookie(name, value) {
            var days = 1;
            var exp = new Date();
            exp.setTime(exp.getTime() + days * 24 * 60 * 60 * 1000);
            document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString() + ";path=/";
        }*/
        Date exp = new Date(System.currentTimeMillis()+24 * 60 * 60 * 1000);
        return name + "=" + escape(value) + ";expires=" + exp.toGMTString() + ";path=/";
    }

    public static void syncCookie(WebView view,Context context){
        CookieManager cookieManager = CookieManager.getInstance();
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP){
            CookieSyncManager.createInstance(context);
        }
        cookieManager.setAcceptCookie( true );
        cookieManager.removeSessionCookie();// 移除
        cookieManager.removeAllCookie();
//        StringBuilder sbCookie = new StringBuilder();//创建一个拼接cookie的容器,为什么这么拼接，大家查阅一下http头Cookie的结构
//        sbCookie.append(cookies);//拼接sessionId
//                 sbCookie.append(String.format(";domain=%s", ""));
//                 sbCookie.append(String.format(";path=%s", ""));
        for (String cookie:getCookieList()) {
            cookieManager.setCookie(MyConst.HOST_NAME, cookie);//为url设置cookie
            CookieSyncManager.getInstance().sync();//同步cookie
            String newCookie = cookieManager.getCookie(MyConst.HOST_NAME);
            LogUtil.i("ui", newCookie);
        }
    }

    public static void saveUserType(String userType) {
        saveString("userType",userType);
    }
}
